/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/*
 * PostMessage.java
 *
 * Created on Feb 20, 2011, 2:44:10 PM
 */
package edu.rit.varapp.graphical;

import edu.rit.varapp.datalayer.Customer;
import edu.rit.varapp.datalayer.CustomerOps;
import edu.rit.varapp.datalayer.Message;
import edu.rit.varapp.datalayer.Post;
import edu.rit.varapp.utilities.ExceptionUtils;
import java.awt.Dimension;
import java.sql.SQLException;
import java.util.ArrayList;
import javax.swing.JOptionPane;

import static edu.rit.varapp.utilities.StringUtils.escapeSpecialCharacters;
/**
 *
 * @author Eric Kisner
 */
public class PostMessage extends AbstractView {

    private final CustomerOps cOps = new CustomerOps();
    private static final int VIEW_WIDTH = 560;
    private static final int VIEW_HEIGHT = 290;
    private AdminOperations parent;
    private Post post;

    /** Creates new form PostMessage */
    public PostMessage( AdminOperations parent, Post post ) {
        super( new Dimension( VIEW_WIDTH, VIEW_HEIGHT ) );
        this.parent = parent;
        this.post = post;
        initComponents();
    }

    /**
     * If the user has not typed the customer's name in exactly, they may get more than one customer,
     * so we should prompt the user to ask which user they actually meant to post the message to.
     * @param customers The list of customers like the given name.
     * @return The customer that the user actually meant, or null if we couldn't find the correct customer.
     */
    private Customer getCorrectCustomer( ArrayList<Customer> customers, String nameToLookFor ) {
        for( Customer customer : customers ) {
            int selection = JOptionPane.showConfirmDialog( this,
                                                           "Did you mean customer: "
                                                           + customer.getContactName() + " "
                                                           + "@ company: " + customer.getCompanyName() + " for '"
                                                           + nameToLookFor + "'?",
                                                           "Select the correct Customer",
                                                           JOptionPane.YES_NO_OPTION );
            if( selection == JOptionPane.YES_OPTION ) {
                return customer;
            }
        }
        return null;
    }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings( "unchecked" )
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {
        java.awt.GridBagConstraints gridBagConstraints;

        jScrollPane1 = new javax.swing.JScrollPane();
        messageArea = new javax.swing.JTextArea();
        jPanel1 = new javax.swing.JPanel();
        postMessageButton = new javax.swing.JButton();
        clearMessageButton = new javax.swing.JButton();
        jPanel2 = new javax.swing.JPanel();
        jLabel1 = new javax.swing.JLabel();
        specificCustomersField = new javax.swing.JTextField();
        jLabel2 = new javax.swing.JLabel();
        subjectField = new javax.swing.JTextField();
        jPanel3 = new javax.swing.JPanel();

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
        setTitle("Post Message");
        setAlwaysOnTop(true);
        setMinimumSize(new java.awt.Dimension(560, 290));
        setResizable(false);
        addWindowListener(new java.awt.event.WindowAdapter() {
            public void windowClosed(java.awt.event.WindowEvent evt) {
                formWindowClosed(evt);
            }
        });

        messageArea.setColumns(20);
        messageArea.setLineWrap(true);
        messageArea.setRows(5);
        messageArea.setWrapStyleWord(true);
        jScrollPane1.setViewportView(messageArea);

        jPanel1.setLayout(new java.awt.GridBagLayout());

        postMessageButton.setText("Post Message");
        postMessageButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                postMessageButtonActionPerformed(evt);
            }
        });
        gridBagConstraints = new java.awt.GridBagConstraints();
        gridBagConstraints.gridwidth = 10;
        gridBagConstraints.gridheight = 3;
        gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL;
        gridBagConstraints.ipadx = 50;
        gridBagConstraints.ipady = 10;
        gridBagConstraints.insets = new java.awt.Insets(15, 25, 15, 25);
        jPanel1.add(postMessageButton, gridBagConstraints);

        clearMessageButton.setText("Clear Message");
        clearMessageButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                clearMessageButtonActionPerformed(evt);
            }
        });
        gridBagConstraints = new java.awt.GridBagConstraints();
        gridBagConstraints.gridwidth = 10;
        gridBagConstraints.gridheight = 3;
        gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL;
        gridBagConstraints.ipadx = 50;
        gridBagConstraints.ipady = 10;
        gridBagConstraints.insets = new java.awt.Insets(15, 25, 15, 25);
        jPanel1.add(clearMessageButton, gridBagConstraints);

        jPanel2.setLayout(new java.awt.GridBagLayout());

        jLabel1.setText("Specify Customers (comma-separated names):");
        gridBagConstraints = new java.awt.GridBagConstraints();
        gridBagConstraints.insets = new java.awt.Insets(10, 25, 10, 25);
        jPanel2.add(jLabel1, gridBagConstraints);
        gridBagConstraints = new java.awt.GridBagConstraints();
        gridBagConstraints.ipadx = 250;
        gridBagConstraints.insets = new java.awt.Insets(10, 0, 10, 25);
        jPanel2.add(specificCustomersField, gridBagConstraints);

        jLabel2.setText("Subject:");
        gridBagConstraints = new java.awt.GridBagConstraints();
        gridBagConstraints.gridx = 0;
        gridBagConstraints.gridy = 2;
        gridBagConstraints.insets = new java.awt.Insets(10, 25, 10, 25);
        jPanel2.add(jLabel2, gridBagConstraints);
        gridBagConstraints = new java.awt.GridBagConstraints();
        gridBagConstraints.gridx = 1;
        gridBagConstraints.gridy = 2;
        gridBagConstraints.ipadx = 250;
        gridBagConstraints.insets = new java.awt.Insets(10, 0, 10, 25);
        jPanel2.add(subjectField, gridBagConstraints);

        jPanel3.setLayout(new java.awt.GridBagLayout());

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, 560, Short.MAX_VALUE)
            .addComponent(jPanel2, javax.swing.GroupLayout.DEFAULT_SIZE, 560, Short.MAX_VALUE)
            .addComponent(jPanel3, javax.swing.GroupLayout.DEFAULT_SIZE, 560, Short.MAX_VALUE)
            .addComponent(jScrollPane1, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, 560, Short.MAX_VALUE)
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 138, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jPanel3, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jPanel2, javax.swing.GroupLayout.DEFAULT_SIZE, 84, Short.MAX_VALUE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, 45, javax.swing.GroupLayout.PREFERRED_SIZE))
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void formWindowClosed(java.awt.event.WindowEvent evt) {//GEN-FIRST:event_formWindowClosed
        parent.setEnabled( true );
        parent.repaint();
        parent.validate();
        parent.toFront();   //Once we repaint the administrator view, we want to bring it to the front for convenience.
    }//GEN-LAST:event_formWindowClosed

    private void postMessageButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_postMessageButtonActionPerformed
        String textArea = escapeSpecialCharacters(messageArea.getText());
        String subjectArea = escapeSpecialCharacters(subjectField.getText());
        if( specificCustomersField.getText().isEmpty() ) {
            try {
                //Get all customers in the database
                ArrayList<Customer> allCustomers = cOps.retrieveCustomers( "" );
                for( Customer customer : allCustomers ) {
                    Message m = new Message( 0, customer.getEntityId(), textArea, subjectArea );
                    post.insertMessage( m );
                }
                JOptionPane.showMessageDialog( this, "Successfully posted message to all customers." );
                this.dispose();
            } catch( SQLException sqle ) {
                ExceptionUtils.handleException( this, sqle, "There was an error retrieving all customer.\n"
                                                            + "Please check the log files for more details.",
                                                this.getClass() );
                return;
            }

        } else {
            String[] names = specificCustomersField.getText().split( "," );
            try {
                for( String name : names ) {
                    name = name.trim();
                    if( name.isEmpty() || name.contains( "\n" ) ) {
                        //We don't want the admin to enter nothing and have to go through every single customer.
                        continue;
                    }
                    Customer toMessage = null;
                    ArrayList<Customer> customers = cOps.retrieveCustomers( name );
                    if( customers.size() > 1 ) {
                        toMessage = getCorrectCustomer( customers, name );
                    } else if( customers.size() == 1 ) {
                        toMessage = customers.get( 0 );
                    }

                    if( toMessage == null ) {
                        JOptionPane.showMessageDialog( this, "The customer with name " + name + " could not be found."
                                                             + "\nPlease check that you have spelled it correctly." );
                        continue;
                    }
                    Message m = new Message( 0, toMessage.getEntityId(), textArea, subjectArea );
                    post.insertMessage( m );
                }
                JOptionPane.showMessageDialog( this, "Successfully posted message to specific customers." );
                this.dispose();
            } catch( SQLException sqle ) {
                ExceptionUtils.handleException( this, sqle, "There was an error when posting a new message."
                                                            + "\nPlease check the log files for more details.",
                                                this.getClass() );
                return;
            }
        }
    }//GEN-LAST:event_postMessageButtonActionPerformed

    private void clearMessageButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_clearMessageButtonActionPerformed
        messageArea.setText( "" );
        specificCustomersField.setText( "" );
    }//GEN-LAST:event_clearMessageButtonActionPerformed
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton clearMessageButton;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JPanel jPanel2;
    private javax.swing.JPanel jPanel3;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JTextArea messageArea;
    private javax.swing.JButton postMessageButton;
    private javax.swing.JTextField specificCustomersField;
    private javax.swing.JTextField subjectField;
    // End of variables declaration//GEN-END:variables
}
